package com.mfs.proxy.core.message.mailbox;

import com.alibaba.fastjson2.JSON;
import com.mfs.proxy.core.exceptions.ProxyException;
import com.mfs.proxy.core.client.config.ClientConfig;
import com.mfs.proxy.core.enums.MessageTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.channels.SelectionKey;

/**
 * 邮箱抽象实现
 *
 * @author mfs
 * @date 2023/7/2 12:33
 **/
public abstract class AbstractCommunicationMailbox implements CommunicationMailbox {
    private final static Logger logger = LoggerFactory.getLogger(AbstractCommunicationMailbox.class);
    /**
     * 客户端通信句柄
     * */
    protected SelectionKey communicationSelectionKey;

    public AbstractCommunicationMailbox(SelectionKey selectionKey) {
        this.communicationSelectionKey = selectionKey;
    }

    @Override
    public void send(MessageTypeEnum messageType) throws IOException {
        Object messageContent = null;
        switch (messageType) {
            case CONNECT:
                messageContent = ClientConfig.getInstance();
                break;
            case CLOSE:
            case HEART_BEAT:
                messageContent = ClientConfig.getInstance().getProxyHandle();
                break;
            case CONNECTED:
            case CHANNEL_REQUEST:
            case CHANNEL_RESPONSE:
                throw new ProxyException(new IllegalArgumentException("消息内容无法确定"));
            default: throw new ProxyException("不支持的消息类型");
        }
        send(messageType, messageContent);
    }

    @Override
    public void send(MessageTypeEnum messageType, Object messageContent) throws IOException {
        logger.debug("正在向客户端发送消息，消息类型：{}，消息内容：{}", messageType.getDescribe(), JSON.toJSONString(messageContent));
        messageType.getMessageSendProcessor().send(communicationSelectionKey, messageType, messageContent);
    }

    @Override
    public void close() throws IOException {
        communicationSelectionKey.channel().close();
        communicationSelectionKey.cancel();
    }
}
